<template>
    <div class="choose-object">
        <a-select
            v-model="myManager"
            mode="multiple"
            class="select-manager"
            option-label-prop="label"
            :disabled="optFlag==3"
            @search="selectSearch"
            @focus="searchData=[]"
            @select="selectEvent"
            @change="selectChange"
        >
        <a-select-option v-for="item in searchData" :key="item.id" :value="item.type+'/'+item.id+'/'+item.name" :label="item.name">{{item.name}}</a-select-option>
      </a-select>
      <a-button :disabled="optFlag==3" style="width:64px" type="primary" @click="chooseEvent">选择</a-button>
    <a-modal
      :title="modalTitle"
      :visible="myVisible"
      centered
      width="800px"
      :maskClosable="false"
      @cancel="myVisible=false"
    >   
        <div class="quik-search">
            <span>快速查询：</span>
            <a-input  v-model="keywords" @pressEnter="quikSearch"/>
            <a-button type="primary" @click="quikSearch">查询</a-button>
        </div>
        <div class="card-container">
            <a-tabs type="card">
                <a-tab-pane key="1" tab="单位" v-if="show===''||show.indexOf('g')>-1">
                    <div class="tree-select">
                        <Atree
                            ref="unitTree"
                            :treePos="false"
                            :request-flag="4"
                            :checkStrictly="true"
                            :single="single"
                            @selectFunc='selectT'
                            @checkFunc='checkT'
                            :menuIds="unitIds"
                            :checkable="type.indexOf('g')>-1"
                        ></Atree>
                    </div>
                </a-tab-pane>
                <a-tab-pane key="2" tab="工作组" v-if="show===''||show.indexOf('t')>-1">
                    <div class="tree-select">
                        <Atree
                            ref="workTree"
                            :treePos="false"
                            :request-flag="5"
                            :checkStrictly="true"
                            :single="single"
                            @selectFunc='selectT'
                            @checkFunc='checkT'
                            :menuIds="teamIds"
                            :checkable="type.indexOf('t')>-1"
                        ></Atree>
                    </div>
                </a-tab-pane>
                <a-tab-pane key="3" tab="角色" v-if="show===''||show.indexOf('r')>-1">
                    <div class="tree-select">
                        <Atree
                            ref="roleTree"
                            :treePos="false"
                            :request-flag="6"
                            :checkable="type.indexOf('r')>-1"
                            @selectFunc= 'selectT'
                            :checkStrictly="true"
                            :single="single"
                            @checkFunc='checkT'
                            :menuIds="roleIds"
                        ></Atree>
                    </div>
                </a-tab-pane>
            </a-tabs>
        </div>
        <div class="right-choice">
            <span class="right-title">选择对象</span>
            <ul class="data-type">
                <li v-show="searchUnit.length">
                    <div class="list-title">
                        <span>组织机构</span>
                        <a-checkbox v-if="!single" v-model="unitAll"  @change="checkAll('unitAll','checkedUnit','searchUnit')" class="check-all">全选</a-checkbox>
                    </div>
                    <div class="check-list">
                        <!-- 可选对象 -->
                        <a-radio-group v-model="checkedUnit" v-if="single" @change="checkEvent('checkedUnit','searchUnit')">
                            <a-radio v-for="item in searchUnit" :value="item.id" :key="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                        <a-checkbox-group
                            v-if="!single"
                            v-model="checkedUnit"
                            @change="checkEvent('checkedUnit','searchUnit','unitAll')"
                        >
                            <a-checkbox v-for="item in searchUnit" :value="item.id" :key="item.id">{{item.name}}</a-checkbox>
                        </a-checkbox-group>
                    </div>
                </li>
                <li v-show="searchTeam.length">
                    <div class="list-title">
                        <span>工作组</span>
                        <a-checkbox v-if="!single" v-model="teamAll" @change="checkAll('teamAll','checkedTeam','searchTeam')" class="check-all">全选</a-checkbox>
                    </div>
                    <div class="check-list">
                        <!-- 可选对象 -->
                        <a-radio-group v-model="checkedTeam" v-if="single" @change="checkEvent('checkedTeam','searchTeam')">
                            <a-radio v-for="item in searchTeam" :value="item.id" :key="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                        <a-checkbox-group
                            v-if="!single"
                            v-model="checkedTeam"
                            @change="checkEvent('checkedTeam','searchTeam','teamAll')"
                        >
                            <a-checkbox v-for="item in searchTeam" :value="item.id" :key="item.id">{{item.name}}</a-checkbox>
                        </a-checkbox-group>
                    </div>
                </li>
                <li v-show="searchRole.length">
                    <div class="list-title">
                        <span>角色</span>
                        <a-checkbox v-if="!single" v-model="roleAll" @change="checkAll('roleAll','checkedRole','searchRole')" class="check-all">全选</a-checkbox>
                    </div>
                    <div class="check-list">
                        <!-- 可选对象 -->
                        <a-radio-group v-model="checkedRole" v-if="single" @change="checkEvent('checkedRole','searchRole')">
                            <a-radio v-for="item in searchRole" :value="item.id" :key="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                        <a-checkbox-group
                            v-if="!single"
                            v-model="checkedRole"
                            @change="checkEvent('checkedRole','searchRole','roleAll')"
                        >
                            <a-checkbox v-for="item in searchRole" :value="item.id" :key="item.id">{{item.name}}</a-checkbox>
                        </a-checkbox-group>
                    </div>
                </li>
                <li v-show="searchUser.length">
                    <div class="list-title">
                        <span>用户列表</span>
                        <a-checkbox v-if="!single" v-model="userAll" @change="checkAll('userAll','checkedUser','searchUser')" class="check-all">全选</a-checkbox>
                    </div>
                    <div class="check-list">
                        <!-- 可选对象 -->
                        <a-radio-group v-model="checkedUser" v-if="single" @change="checkEvent('checkedUser','searchUser')">
                            <a-radio v-for="item in searchUser" :value="item.id" :key="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                        <a-checkbox-group
                            v-if="!single"
                            v-model="checkedUser"
                            @change="checkEvent('checkedUser','searchUser','userAll')"
                        >
                            <a-checkbox v-for="item in searchUser" :value="item.id" :key="item.id">{{item.name}}</a-checkbox>
                        </a-checkbox-group>
                    </div>
                </li>
            </ul>
           
            <span class="area-split"></span>
            <div class="checked-tags">
                <!-- 已选择对象 -->
                <a-tag v-for="(item,i) in checkedArr" :key="item.id" color="blue" closable @close="tagClose(item.id,i,item.type)">{{item.name}}</a-tag>
            </div>
        </div>
        <template slot="footer">
            <div class="footer-btns">
                <a-button type="primary" @click="handleOk">确定</a-button>
                <a-button @click="reset">清空</a-button>
                <a-button @click="myVisible=false">取消</a-button>
            </div>
      </template>
    </a-modal>
    </div>
</template>

<script>
import Atree from 'components/base/atree';
import { selectUser,userSearch } from "@/api/component";
export default {
  components: {
    Atree
  },
  data() {
    return {
        myManager:[],
        searchData:[],
        listTitle:'',
        myVisible: false,
        keywords:'',
        checkedArr: [],//当前已选对象列表
        searchUnit:[],//模糊搜素组织机构数据
        searchTeam:[],//模糊搜素工作组数据
        searchUser:[],//模糊搜素用户列表数据
        searchRole:[],//模糊搜素角色列表数据
        checkedUnit:[],//当前已选组织机构列表
        checkedTeam:[],//当前已选工作组列表
        checkedUser:[],//当前已选对象列表
        checkedRole:[],//当前已选角色列表
        unitAll:false,
        teamAll:false,
        userAll:false,
        roleAll:false,
        unitIds:[],//单位树复选框选择
        teamIds:[],//工作组复选框选择
        roleIds:[],//角色复选框选择
    };
  },
  props: {
    show:{ //''全部展示  g/t/r 单位/工作组/角色 分情况展示
        type:String,
        default:''
    },
    type:{//u 树只查对象  u+g/t/r 树节点带复选框
        type:String,
        default:'u'
    },
    manager:{  //选中用的角色
        type:Array,
        default: null
    },
    single:{ //是否多选
        type: Boolean,
        default: false
    },
    modalTitle:{ //弹出层名字
        type: String,
        default:'选择机构用户'
    },
    optFlag:{
        type: Number,
        default: 1  // 1新增 2编辑 3查询
    },
  },
  mounted(){
    this.myManager = this.manager;
    this.myManager.forEach(item=>{
        let arr = item.split('/')
        this.searchData.push({type:arr[0],id:arr[1],name:arr[2]});
    });
  },
  methods: {
    //选择
    chooseEvent(){
        this.myVisible=!this.myVisible;
        this.checkedArr = [];
        this.myManager.forEach(item=>{
            let datas = item.split('/');
            this.checkedArr.push({type:datas[0],id:datas[1],name:datas[2]});
        });
        this.renderTree();
        this.renderCheck('checkedUnit', 'searchUnit', 'unitAll');
        this.renderCheck('checkedTeam', 'searchTeam', 'teamAll');
        this.renderCheck('checkedUser', 'searchUser', 'userAll');
        this.renderCheck('checkedRole', 'searchRole', 'roleAll');
    },
    //下拉搜索
    selectSearch(val){
        this.searchData = [];
        if(!val){
            return false;
        }
        userSearch({keywords:val,rootId:'',type:this.type}).then((res) => {
            let data = res.data.data;
            if(data.userList){
                 data.userList.forEach(item=>{
                    item.type='u';
                    item.name=item.cname;
                    this.searchData.push(item);
                });
            }
            if(data.unitList){
                data.unitList.forEach(item=>{
                    item.type='g';
                    item.name = item.unitName;
                    this.searchData.push(item);
                })
            }
            if(data.teamList){
                data.teamList.forEach(item=>{
                    item.type='t';
                    item.name = item.teamName;
                    this.searchData.push(item);
                })
            }
            if(data.roleList){
                data.roleList.forEach(item=>{
                    item.type='r';
                    this.searchData.push(item);
                })
            }
        }).catch((err)=>{
            this.$message.destroy();
            this.$message.error(err);
        });
    },
    //下拉选中
    selectEvent(val){
        if(this.single){
            this.myManager = [val];
        }
    },
    //全选
    checkAll(allV,modelV,dataV){
        if(this[allV]){
            this[dataV].forEach(x=>{
                if(!this.checkedArr.some(y=>x.id===y.id)){
                    this[modelV].push(x.id);
                    this.checkedArr.push(x);
                }
            })
        }else{
            this[modelV] = [];
            this.checkedArr = this.checkedArr.filter(x=>{
                return !this[dataV].some(y=>x.id===y.id)
            })
        }
        this.renderTree();
    },
    //复选框查询数据
    checkT(requestFlag,val,node){
        let id = node.eventKey,
            type = requestFlag===4?'g':requestFlag==='5'?'t':'r',
            modelV = requestFlag===4?'checkedUnit':requestFlag===5?'checkedTeam':'checkedRole';
        this[requestFlag===4?'unitIds':requestFlag===5?'teamIds':'roleIds'] = val;
        if(!node.checked){
            if(this.single){
                this[modelV]=id;
                this.checkedArr=[{id:id,type:type,name:node.title}];
            }else{
                this[modelV].push(id);
                this.checkedArr.push({id:id,type:type,name:node.title});
            }
        }else{
             if(this.single){
                this[modelV]='';
                this.checkedArr=[];
            }else{
                this[modelV].splice(this[modelV].findIndex(item=>item===id),1);
                this.checkedArr.splice(this.checkedArr.findIndex(item=>item.id===id),1);
            }
        }
        this.renderCheck(modelV, requestFlag===4?'searchUnit':requestFlag===5?'searchTeam':'searchRole', requestFlag===4?'unitAll':requestFlag===5?'teamAll':'roleAll');
    },
    //点击树查询数据
    selectT(requestFlag,val,isLeaf){
        this.searchUser=this.searchTeam=this.searchUnit=[];
        this.userAll=this.teamAll=this.unitAll=false;
        let type = isLeaf?'u':requestFlag==4?(this.type.indexOf('g')>-1?'g':'u'):(this.type.indexOf('t')>-1?'t':'u'),
            params={type:type,unitId:'',teamId:'',roleId:''};
        params[requestFlag==4?'unitId':requestFlag==5?'teamId':'roleId']=val;
        this.loading = true;
        selectUser(params).then((res) => {
            let data = res.data.data,
                dataV = type==='u'?'searchUser':type==='g'?'searchUnit':type==='t'?'searchTeam':'searchRole',
                listV = type==='u'?'userList':type==='g'?'unitList':type==='t'?'teamList':'roleList';
            data[listV].forEach(item=>{
                item.type=type;
                if(type==='u'){
                    item.name = item.cname;
                }
            });
            this[dataV] = data[listV];
            this.renderCheck(type==='u'?'checkedUser':type==='g'?'checkedUnit':type==='t'?'checkedTeam':'checkedRole',dataV,type==='u'?'userAll':type==='g'?'unitAll':type==='t'?'teamAll':'roleAll');
        }).catch((err)=>{
            this.$message.destroy();
            this.$message.error(err);
        }).finally(() => {
            this.loading = false;
        });
    },
    //快速查询
    quikSearch(){
        if(!this.keywords){
            this.$message.warning('请输入关键字');
            return false;
        }
        this.loading = true;
        this.searchUnit = this.searchTeam = this.searchUser = [];
        userSearch({keywords:this.keywords,rootId:'',type:this.type}).then((res) => {
            let data = res.data.data;
            if(data.userList){
                data.userList.forEach(item=>{
                    item.type='u';
                    item.name=item.cname;
                });
                this.searchUser=data.userList;
                this.renderCheck('checkedUser','searchUser','userAll');
            }
            if(data.unitList){
                data.unitList.forEach(item=>{
                    item.type='g';
                    item.name = item.unitName;
                })
                this.searchUnit=data.unitList;
                this.renderCheck('checkedUnit','searchUnit','unitAll');
            }
            if(data.teamList){
                data.teamList.forEach(item=>{
                    item.type='t';
                    item.name = item.teamName;
                })
                this.searchTeam=data.teamList;
                this.renderCheck('checkedTeam','searchTeam','teamAll');
            }
            if(data.roleList){
                data.roleList.forEach(item=>{
                    item.type='r';
                })
                this.searchRole=data.roleList;
                this.renderCheck('checkedRole','searchRole','roleAll');
            }
        }).catch((err)=>{
            this.$message.destroy();
            this.$message.error(err);
        }).finally(() => {
            this.loading = false;
        });
    },
    //切换数据 渲染已勾选
    renderCheck(modelV,dataV,allV){
        if(this.single){
            this[modelV] = '';
            let findIndex = this.checkedArr.findIndex(x=>this[dataV].some(y=>x.id===y.id));
            if(findIndex>-1){
                this[modelV] = this.checkedArr[findIndex].id;
            }
        }else{
            this[modelV] = [];
            this.checkedArr.forEach(x=>{
                if(this[dataV].some(y=>x.id===y.id)){
                     this[modelV].push(x.id);
                }
            });
            this[allV] = this[modelV].length === this[dataV].length?true:false;
        }
    },
    //对象列表选择
    checkEvent(modelV,dataV,allV){
        if(this.single){
            this.checkedArr=[{id:this[modelV]}];
            let item = this[dataV][this[dataV].findIndex(item=>item.id===this[modelV])];
            this.checkedArr[0].name = item.name;
            this.checkedArr[0].type = item.type;
        }
        if(!this.single){
            //当前对象已勾选
            let tempArr = this[dataV].filter(a=>a.id === this[modelV].filter(b=>a.id===b)[0]);
            //当前对象未勾选
            let tempRemove = this[dataV].filter(x=>tempArr.every(y=>x.id!==y.id));
            //添加已勾选
            tempArr.forEach((tItem)=>{
                if(!this.checkedArr.some(cdItem=>cdItem.id===tItem.id)){
                    this.checkedArr.push(tItem);
                }
            })
            //删除已选中的 当前未勾选
            tempRemove.forEach((tItem)=>{
                let removeIndex = this.checkedArr.findIndex(item=>item.id===tItem.id);
                if(removeIndex>-1){
                    this.checkedArr.splice(removeIndex,1);
                }
            })
            this[allV] = tempRemove.length?false:true;
        }
        this.renderTree();
    },
    //同步树勾选数据
    renderTree(){
        this.unitIds = this.teamIds = this.roleIds = [];
        this.checkedArr.forEach(item=>{
            let id = item.id;
            if(item.type==='g'){
                this.unitIds.push(id);
            }else if(item.type==='t'){
                this.teamIds.push(id);
            }else{
                this.roleIds.push(id);
            }
        });
    },
    //删除已选对象
    tagClose(id,index,type){
        let modelV = type==='u'?'checkedUser':type==='g'?'checkedUnit':type==='t'?'checkedTeam':'checkedRole';
        this.checkedArr.splice(index,1);
        if(this.single){
            this[modelV] = '';
        }
        if(!this.single){
            let index = this[modelV].findIndex(item=>item===id);
            //取消当前对象列表勾选项
            if(index>-1){
                this[modelV].splice(index,1)
                this[type==='u'?'userAll':type==='g'?'unitAll':type==='t'?'teamAll':'roleAll'] = false;
            }
        }
        this.renderTree();
    },
    //确定
    handleOk(){
        this.myManager = [];
        this.checkedArr.forEach(item=>{
            this.myManager.push(item.type+'/'+item.id+'/'+item.name);
        });
        this.myVisible = false;
        this.searchData = this.checkedArr;
        this.$emit('selectFunc',this.checkedArr);
    },
    selectChange(value){
         //this.checkedArr = value
         var itemArr = []
         var valueArr = []
         value.forEach((item, index) => {
            var obj = {}
            itemArr = item.split("/")
            obj.type = itemArr[0]
            obj.id= itemArr[1]
            obj.name= itemArr[2]
            valueArr.push(obj)
        });
        this.$emit('selectFunc',valueArr);
    },
    //清空
    reset(){
        this.keywords = '';
        this.checkedArr = [];
        this.checkedUser = this.checkedUnit = this.checkedTeam = '';
        this.userAll = this.unitAll = this.teamAll = false;
        this.unitIds = this.teamIds = this.roleIds = [];
    },
    //返回勾选的对象给父组件
    getData(){
        return this.checkedArr;
    }
  },
  computed: {},
  watch: {
  }
};
</script>

<style lang="stylus">
@import '~stylus/mixin.styl';
.choose-object
    .select-manager
        width calc(100% - 74px)
        margin-right 10px
.footer-btns
    width 100%
    height 100%
    text-align center
.quik-search
    height 46px
    line-height 32px
    padding-bottom 14px
    border-bottom 1px solid #e8e8e8
    input
        width 500px
        margin-right 15px
.card-container
    display inline-block
    background #f5f5f5
    border-radius 4px
    border 1px solid #f5f5f5
    model(33%, none, 14px 0 0 0, none, -1, 0)
    shadow(0 0 6px 0 #e2e2e2)
    .ant-tabs-card
        .ant-tabs-content
            height 100%
            margin-top -16px
            .ant-tabs-tabpane
                background #fff
                padding 0
        .ant-tabs-bar
            border-color #fff
            .ant-tabs-nav-scroll 
                background-color #f5f5f5
            .ant-tabs-tab
                border-color transparent
                background transparent
                border-radius 0
            .ant-tabs-tab-active
                border-color #fff
                background #fff
    .tree-select
        height 350px
        overflow auto
.right-choice
    display: inline-block;
    width 65%
    border-radius 4px
    border 1px solid #f5f5f5
    model(calc(67% - 15px), 392px, 14px 0 0 15px, none, -1, 0)
    shadow(0 0 6px 0 #e2e2e2)
    .right-title
        display block
        background-color #f5f5f5
        height 40px
        line-height 40px
        padding-left 16px
    .data-type
        height 260px
        overflow-y auto
    .list-title
        line-height 40px
        model(none, 40px, 0 15px, 0 0 0 5px, -1, -1)
        border-bottom 1px solid #e8e8e8
        .check-all
            float right
    .check-list
        max-height 190px
        model(none, none, 12px 15px 0 5px, none, -1, 3)
        .ant-radio-wrapper
            margin 0 0 10px 10px
        .ant-checkbox-wrapper
            margin 0 0 10px 10px
    .area-split
        display block
        margin 0 15px
        height 1px
        background-color #f5f5f5
        shadow(0 0 1px 0 #e2e2e2)
    .checked-tags
        model(none, 70px, 12px 15px 12px 5px, none, -1, 3)
        .ant-tag
            margin 0 0 10px 10px
            height 25px
            line-height 25px
            .anticon-close
                font-size 14px
                color #1890ff
                &:hover
                    color #1890ff
</style>